package com.supplychain.scm.core.common.validator.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * @author liyichuan
 * @date 2022/06/11
 */
@Slf4j
public class FileSizeConstraintValidator implements ConstraintValidator<FileSize, MultipartFile> {

    private String size;
    /**
     * 校验器初始化
     * @param constraintAnnotation
     */
    @Override
    public void initialize(FileSize constraintAnnotation) {
        //获取注解的中制定的值
         size = constraintAnnotation.value();
    }


    @Override
    public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext constraintValidatorContext) {
        // 空不做校验
        if(null == multipartFile){
            return true;
        }

        long orgSize = multipartFile.getSize();
        // kb
        BigDecimal orgKb = new BigDecimal(orgSize).divide(new BigDecimal(1024), 2, BigDecimal.ROUND_DOWN);

        if(orgKb.compareTo(new BigDecimal(size)) < 0){
            return true;
        }

        return false;
    }
}
